package com.usbserial.driver;

import android.hardware.usb.UsbDevice;
import android.hardware.usb.UsbDeviceConnection;

import com.felhr.usbserial.UsbSerialDevice;
import com.usbserial.exception.DriverNotFoundException;

/**
 * Creates driver instances backed by the felHR usb-serial implementations.
 */
public final class DriverFactory {

    private DriverFactory() {
    }

    public static UsbSerialDriver createDriver(UsbDevice device,
                                               UsbDeviceConnection connection,
                                               DriverType driverType,
                                               int interfaceIndex) throws DriverNotFoundException {
        UsbSerialDevice serialDevice;
        if (driverType == null) {
            driverType = DriverType.AUTO;
        }

        if (driverType == DriverType.AUTO) {
            serialDevice = UsbSerialDevice.createUsbSerialDevice(device, connection, interfaceIndex);
        } else {
            serialDevice = UsbSerialDevice.createUsbSerialDevice(driverType.getLegacyName(), device, connection, interfaceIndex);
        }

        if (serialDevice == null) {
            throw new DriverNotFoundException("No USB serial driver available for device " + device.getDeviceName());
        }

        return new FelhrUsbSerialDriver(serialDevice);
    }
}
